// 监听键盘事件的函数
function handleKeyDown(e) {
  // 检查快捷键是否启用
  chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
    if (result.hotkeyEnabled === false) return;
    
    // 只在按下F键时触发
    if (e.key === 'f' || e.key === 'F') {
      // 防止其他功能被触发
      e.preventDefault();
      
      // 查找当前正在播放的视频
      const videos = document.querySelectorAll('video');
      const playingVideo = Array.from(videos).find(video => !video.paused);
      
      if (playingVideo) {
        // 尝试查找视频播放器的全屏按钮
        let fullscreenButton = findFullscreenButton(playingVideo);
        
        if (fullscreenButton) {
          // 模拟点击全屏按钮
          fullscreenButton.click();
        } else {
          // 如果找不到全屏按钮，使用HTML5的全屏API
          toggleFullscreen(playingVideo);
        }
      }
    }
  });
}

// 查找视频播放器的全屏按钮
function findFullscreenButton(video) {
  // 获取视频元素的父元素（通常是视频播放器的容器）
  const playerContainer = video.parentElement;
  
  if (!playerContainer) return null;
  
  // 常见的全屏按钮选择器
  const selectors = [
    '.ytp-fullscreen-button',          // YouTube
    '.bpx-player-ctrl-fullscreen-btn', // B站
    '.vjs-fullscreen-control',         // Video.js
    '.fullscreen',                     // 通用
    '[title="全屏"]',                  // 中文标题
    '[aria-label="全屏"]',             // 中文ARIA标签
    '[title="Full screen"]',           // 英文标题
    '[aria-label="Full screen"]',      // 英文ARIA标签
    '[data-title-no-tooltip="全屏"]',  // 腾讯视频
    '.txp-fullscreen-btn'              // 腾讯视频
  ];
  
  // 尝试在播放器容器中查找全屏按钮
  for (const selector of selectors) {
    const button = playerContainer.querySelector(selector);
    if (button) return button;
  }
  
  // 尝试在整个文档中查找与视频相关的全屏按钮
  for (const selector of selectors) {
    const buttons = document.querySelectorAll(selector);
    for (const button of buttons) {
      // 检查按钮是否与视频在同一父容器中
      if (isAncestor(playerContainer, button)) {
        return button;
      }
    }
  }
  
  return null;
}

// 检查元素是否是另一个元素的祖先
function isAncestor(ancestor, element) {
  let current = element.parentElement;
  while (current) {
    if (current === ancestor) return true;
    current = current.parentElement;
  }
  return false;
}

// 使用HTML5全屏API切换全屏状态
function toggleFullscreen(element) {
  if (!document.fullscreenElement) {
    // 进入全屏
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    }
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
}

// 开始监听键盘事件
function startListening() {
  document.addEventListener('keydown', handleKeyDown);
}

// 停止监听键盘事件
function stopListening() {
  document.removeEventListener('keydown', handleKeyDown);
}

// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'startListening') {
    startListening();
  } else if (request.action === 'stopListening') {
    stopListening();
  }
});

// 页面加载完成后，默认开始监听
chrome.storage.sync.get(['hotkeyEnabled'], (result) => {
  if (result.hotkeyEnabled !== false) {
    startListening();
  }
});
